package com.jokins.admin.vue.hefeng.utils;

import com.alibaba.fastjson2.JSONObject;
import com.jokins.common.actions.exception.BusinessException;
import com.jokins.common.entry.hefeng.Weather;
import com.jokins.common.util.BusinessCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

@Slf4j
public class GetWeatherToDay {

    final static String apiKey = "aa1950307bdf4ba187ca8136bf0f5de4";

    public static Weather API(String cityId) {
        String url = "https://devapi.qweather.com/v7/weather/now?location=" + cityId + "&key=" + apiKey;
        log.info("Sending request to: {}", url);
        Weather weather = new Weather();
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet request = new HttpGet(url);
            try (CloseableHttpResponse response = httpClient.execute(request)) {
                int statusCode = response.getStatusLine().getStatusCode();
                log.info("Received response with status code: {}", statusCode);
                if (statusCode != 200) {
                    log.error("Request failed with status code: {}", statusCode);
                    throw new BusinessException("Request to external API failed with status code: ", BusinessCode.SERVER_ERROR);
                }
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    String responseBody = EntityUtils.toString(entity);
                    JSONObject jsonObject = JSONObject.parseObject(responseBody);
                    String code = jsonObject.getString("code");
                    if (!"200".equals(code)) {
                        log.error("External API returned error code: {}", code);
                        throw new BusinessException("External API returned error code: ", BusinessCode.SERVER_ERROR);
                    }
                    JSONObject now = jsonObject.getJSONObject("now");
                    weather.setCityId(cityId);
                    weather.setText(now.getString("text"));
                    weather.setTemp(now.getString("temp"));
                    weather.setFeelsLike(now.getString("feelsLike"));
                    weather.setWindDir(now.getString("windDir"));
                    weather.setWindScale(now.getString("windScale"));
                    weather.setWindSpeed(now.getString("windSpeed"));
                    weather.setHumidity(now.getString("humidity"));
                    weather.setPrecip(now.getString("precip"));
                    weather.setPressure(now.getString("pressure"));
                    weather.setIcon(now.getString("icon"));
                    weather.setVis(now.getString("vis"));
                    weather.setCloud(now.getString("cloud"));
                    weather.setDew(now.getString("dew"));
                    weather.setWind360(now.getString("wind360"));
                    JSONObject refer = jsonObject.getJSONObject("refer");
                    weather.setSources(refer.getString("sources"));
                    weather.setLicense(refer.getString("license"));
                    weather.setFxLink(jsonObject.getString("fxLink"));
                    String updateTimeStr = jsonObject.getString("updateTime");
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mmXXX", Locale.ROOT);
                    weather.setUpdateTime(LocalDateTime.parse(updateTimeStr, formatter));
                    weather.setObsTime(LocalDateTime.parse(now.getString("obsTime"), formatter));
                    weather.setCode(jsonObject.getString("code"));
                }
            }

        } catch (
                IOException e) {
            log.error("Failed to fetch city data from external API", e);
            throw new BusinessException("Failed to fetch city data from external API", e);
        }
        return weather;
    }
}

